<template>
  <div class="code-block">
    <div class="code-header">
      <div class="header-left">
        <span class="language-tag">{{ languageDisplay }}</span>
        <span v-if="runnable" class="runnable-tag">可运行</span>
      </div>
      <div class="header-right">
        <el-button 
          text 
          size="small" 
          @click="copyCode"
          title="复制代码"
        >
          <el-icon><DocumentCopy /></el-icon>
        </el-button>
        <el-button 
          v-if="runnable" 
          text 
          size="small" 
          @click="runCode"
          title="运行代码"
          :loading="isRunning"
        >
          <el-icon><CaretRight /></el-icon>
        </el-button>
        <el-button 
          text 
          size="small" 
          @click="analyzeCode"
          title="分析代码"
        >
          <el-icon><Search /></el-icon>
        </el-button>
      </div>
    </div>
    
    <div class="code-content">
      <pre><code :class="`language-${language}`" v-html="highlightedCode"></code></pre>
    </div>
    
    <!-- 运行结果 -->
    <div v-if="executionResult" class="execution-result">
      <div class="result-header">
        <span class="result-title">
          <el-icon><Monitor /></el-icon>
          运行结果
        </span>
        <span class="execution-time">{{ executionResult.executionTime }}ms</span>
      </div>
      
      <div v-if="executionResult.output" class="result-output">
        <h5>输出：</h5>
        <pre>{{ executionResult.output }}</pre>
      </div>
      
      <div v-if="executionResult.error" class="result-error">
        <h5>错误：</h5>
        <pre>{{ executionResult.error }}</pre>
      </div>
    </div>
    
    <!-- 代码分析结果 -->
    <div v-if="analysisResult" class="analysis-result">
      <div class="result-header">
        <span class="result-title">
          <el-icon><DataAnalysis /></el-icon>
          代码分析
        </span>
        <span v-if="analysisResult.score" class="analysis-score">
          评分: {{ Math.round(analysisResult.score * 100) }}/100
        </span>
      </div>
      
      <div class="analysis-content">
        <div v-if="analysisResult.suggestions?.length" class="suggestions">
          <h5>改进建议：</h5>
          <ul>
            <li v-for="suggestion in analysisResult.suggestions" :key="suggestion">
              {{ suggestion }}
            </li>
          </ul>
        </div>
        
        <div v-if="analysisResult.issues?.length" class="issues">
          <h5>发现问题：</h5>
          <ul>
            <li v-for="issue in analysisResult.issues" :key="issue" class="issue-item">
              <span class="issue-type">{{ issue.type }}</span>
              <span class="issue-message">{{ issue.message }}</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy, CaretRight, Search, Monitor, DataAnalysis } from '@element-plus/icons-vue'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

interface Props {
  code: string
  language: string
  runnable?: boolean
}

interface ExecutionResult {
  output?: string
  error?: string
  executionTime: number
  memoryUsed?: number
}

interface AnalysisResult {
  score?: number
  suggestions?: string[]
  issues?: Array<{
    type: string
    message: string
    line?: number
  }>
}

const props = withDefaults(defineProps<Props>(), {
  runnable: false
})

const emit = defineEmits<{
  run: [code: string, language: string]
  copy: [code: string]
}>()

// 响应式数据
const isRunning = ref(false)
const executionResult = ref<ExecutionResult | null>(null)
const analysisResult = ref<AnalysisResult | null>(null)

// 计算属性
const languageDisplay = computed(() => {
  const languageMap: Record<string, string> = {
    'javascript': 'JavaScript',
    'typescript': 'TypeScript',
    'java': 'Java',
    'python': 'Python',
    'cpp': 'C++',
    'c': 'C',
    'go': 'Go',
    'rust': 'Rust',
    'php': 'PHP',
    'ruby': 'Ruby',
    'swift': 'Swift',
    'kotlin': 'Kotlin',
    'scala': 'Scala',
    'html': 'HTML',
    'css': 'CSS',
    'sql': 'SQL',
    'bash': 'Bash',
    'powershell': 'PowerShell',
    'json': 'JSON',
    'xml': 'XML',
    'yaml': 'YAML',
    'markdown': 'Markdown'
  }
  return languageMap[props.language.toLowerCase()] || props.language.toUpperCase()
})

const highlightedCode = computed(() => {
  try {
    if (hljs.getLanguage(props.language)) {
      return hljs.highlight(props.code, { language: props.language }).value
    } else {
      return hljs.highlightAuto(props.code).value
    }
  } catch (error) {
    console.error('代码高亮失败:', error)
    return props.code
  }
})

// 方法
const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(props.code)
    ElMessage.success('代码已复制到剪贴板')
    emit('copy', props.code)
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const runCode = async () => {
  if (!props.runnable || isRunning.value) return
  
  isRunning.value = true
  executionResult.value = null
  
  try {
    // 模拟代码执行（实际项目中应该调用后端API）
    await simulateCodeExecution()
    emit('run', props.code, props.language)
  } catch (error: any) {
    ElMessage.error('代码执行失败：' + error.message)
  } finally {
    isRunning.value = false
  }
}

const analyzeCode = async () => {
  try {
    // 模拟代码分析（实际项目中应该调用后端API）
    analysisResult.value = await simulateCodeAnalysis()
    ElMessage.success('代码分析完成')
  } catch (error: any) {
    ElMessage.error('代码分析失败：' + error.message)
  }
}

// 模拟代码执行
const simulateCodeExecution = async (): Promise<void> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 根据语言类型生成不同的模拟结果
      if (props.language === 'java') {
        if (props.code.includes('System.out.println')) {
          executionResult.value = {
            output: 'Hello, World!\n程序执行成功',
            executionTime: Math.floor(Math.random() * 500) + 100,
            memoryUsed: Math.floor(Math.random() * 50) + 20
          }
        } else {
          executionResult.value = {
            output: '编译成功，程序执行完毕',
            executionTime: Math.floor(Math.random() * 300) + 50
          }
        }
      } else if (props.language === 'python') {
        if (props.code.includes('print')) {
          executionResult.value = {
            output: 'Hello, Python!\n执行成功',
            executionTime: Math.floor(Math.random() * 200) + 30
          }
        } else {
          executionResult.value = {
            output: '程序执行完毕',
            executionTime: Math.floor(Math.random() * 150) + 20
          }
        }
      } else if (props.language === 'javascript') {
        if (props.code.includes('console.log')) {
          executionResult.value = {
            output: 'Hello, JavaScript!\n执行成功',
            executionTime: Math.floor(Math.random() * 100) + 10
          }
        } else {
          executionResult.value = {
            output: 'undefined\n执行完毕',
            executionTime: Math.floor(Math.random() * 50) + 5
          }
        }
      } else {
        executionResult.value = {
          output: '代码执行完毕\n（模拟结果）',
          executionTime: Math.floor(Math.random() * 200) + 50
        }
      }
      
      resolve()
    }, 1000 + Math.random() * 1000) // 1-2秒的模拟延迟
  })
}

// 模拟代码分析
const simulateCodeAnalysis = async (): Promise<AnalysisResult> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const suggestions: string[] = []
      const issues: Array<{type: string, message: string, line?: number}> = []
      
      // 基于代码内容的简单分析
      if (props.code.includes('System.out.println') || props.code.includes('print') || props.code.includes('console.log')) {
        suggestions.push('考虑使用日志框架替代直接打印输出')
      }
      
      if (props.code.length > 500) {
        suggestions.push('代码较长，考虑拆分为多个函数或方法')
      }
      
      if (!props.code.includes('//') && !props.code.includes('/*') && !props.code.includes('#')) {
        suggestions.push('建议添加适当的注释来提高代码可读性')
      }
      
      if (props.code.includes('var ') && props.language === 'javascript') {
        issues.push({
          type: '最佳实践',
          message: '建议使用 let 或 const 替代 var'
        })
      }
      
      if (props.code.includes('==') && props.language === 'javascript') {
        issues.push({
          type: '潜在问题',
          message: '建议使用 === 进行严格相等比较'
        })
      }
      
      // 生成评分
      let score = 0.8
      if (issues.length === 0) score += 0.1
      if (suggestions.length <= 2) score += 0.1
      
      resolve({
        score: Math.min(score, 1.0),
        suggestions,
        issues
      })
    }, 800)
  })
}

// 组件挂载时初始化语法高亮
onMounted(() => {
  // 确保highlight.js已加载
  if (typeof hljs !== 'undefined') {
    hljs.configure({ 
      languages: ['javascript', 'typescript', 'java', 'python', 'cpp', 'go', 'rust', 'html', 'css', 'sql']
    })
  }
})
</script>

<style scoped>
.code-block {
  margin: 12px 0;
  border: 1px solid #e1e8ed;
  border-radius: 8px;
  overflow: hidden;
  background: #f8f9fa;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f1f3f4;
  border-bottom: 1px solid #e1e8ed;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.language-tag {
  font-size: 12px;
  font-weight: 500;
  color: #5f6368;
  padding: 2px 6px;
  background: #e8eaed;
  border-radius: 4px;
}

.runnable-tag {
  font-size: 10px;
  color: #1a73e8;
  background: #e8f0fe;
  padding: 2px 4px;
  border-radius: 3px;
  border: 1px solid #dadce0;
}

.header-right {
  display: flex;
  gap: 4px;
}

.code-content {
  background: #fff;
  overflow-x: auto;
}

.code-content pre {
  margin: 0;
  padding: 16px;
  font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
  font-size: 13px;
  line-height: 1.5;
  background: transparent;
}

.code-content code {
  background: transparent;
  padding: 0;
  border-radius: 0;
  font-family: inherit;
}

/* 执行结果样式 */
.execution-result, .analysis-result {
  border-top: 1px solid #e1e8ed;
  background: #f8f9fa;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f1f3f4;
  font-size: 13px;
  font-weight: 500;
}

.result-title {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #5f6368;
}

.execution-time, .analysis-score {
  font-size: 12px;
  color: #1a73e8;
  background: #e8f0fe;
  padding: 2px 6px;
  border-radius: 4px;
}

.result-output, .result-error {
  padding: 12px;
}

.result-output h5, .result-error h5 {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #5f6368;
}

.result-output pre, .result-error pre {
  margin: 0;
  padding: 8px;
  background: #fff;
  border: 1px solid #e1e8ed;
  border-radius: 4px;
  font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
  font-size: 12px;
  line-height: 1.4;
  overflow-x: auto;
}

.result-error pre {
  background: #fef7f7;
  border-color: #fecaca;
  color: #dc2626;
}

/* 分析结果样式 */
.analysis-content {
  padding: 12px;
}

.suggestions, .issues {
  margin-bottom: 16px;
}

.suggestions h5, .issues h5 {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #5f6368;
}

.suggestions ul, .issues ul {
  margin: 0;
  padding-left: 16px;
  font-size: 13px;
}

.suggestions li {
  color: #1a73e8;
  margin-bottom: 4px;
}

.issue-item {
  margin-bottom: 6px;
  display: flex;
  gap: 8px;
  align-items: flex-start;
}

.issue-type {
  font-size: 11px;
  font-weight: 500;
  color: #ea4335;
  background: #fce8e6;
  padding: 2px 4px;
  border-radius: 3px;
  flex-shrink: 0;
}

.issue-message {
  color: #5f6368;
  font-size: 12px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .code-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .header-right {
    align-self: flex-end;
  }
  
  .code-content pre {
    padding: 12px;
    font-size: 12px;
  }
  
  .result-header {
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;
  }
}

/* 语法高亮主题覆盖 */
:deep(.hljs) {
  background: transparent !important;
  padding: 0 !important;
}

:deep(.hljs-keyword) {
  color: #d73a49 !important;
  font-weight: 600;
}

:deep(.hljs-string) {
  color: #032f62 !important;
}

:deep(.hljs-comment) {
  color: #6a737d !important;
  font-style: italic;
}

:deep(.hljs-number) {
  color: #005cc5 !important;
}

:deep(.hljs-function) {
  color: #6f42c1 !important;
}

:deep(.hljs-class) {
  color: #e36209 !important;
  font-weight: 600;
}
</style>
